package com.uniledger.exchange.home.scheme;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuItem;
import android.widget.Button;

import com.uniledger.commonlib.numberkeyboard.KeyboardUtil;
import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.bank.AddBankActivity;
import com.uniledger.exchange.base.activity.BaseActivity;
import com.uniledger.exchange.home.HomeCenter;
import com.uniledger.exchange.home.scheme.fragment.topup.IntoFragment;
import com.uniledger.exchange.home.scheme.fragment.topup.OnTopUpListener;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxProgress;
import com.uniledger.exchange.model.rx.RxSchedulers;

import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 充值页面
 */
public class TopUpActivity extends BaseActivity implements OnTopUpListener {

    @BindView(R.id.btn_confirm)
    Button confirm;

    KeyboardUtil keyboardUtil;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, TopUpActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public void getParams() {
        replaceFragment(IntoFragment.newInstance("", ""), "into");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_up);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            confirm.setStateListAnimator(null);
        }
    }

    @BindString(R.string.topup_bar_title)
    String title;

    @Override
    public void initBar() {
        super.initBar();
        toolbar.setTitle(title);
    }

    private void replaceFragment(Fragment fragment, String name) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.container, fragment, name);
        transaction.addToBackStack(name);
        // Commit the transaction
        transaction.commit();
    }


    @Override
    public void onBackPressed() {
        FragmentManager manager = getSupportFragmentManager();
        int count = manager.getBackStackEntryCount();
        if (count == 1) {
            HomeActivity.start(TopUpActivity.this);
            finish();
        } else if (count == 2) {
            HomeActivity.start(TopUpActivity.this);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 信息填写确认
     */
    @Override
    public void callbackInfo(Map<String, String> params) {
        getKeyboard().hideKeyboard();
        Api.getService().doCharge(params).compose(RxSchedulers.io_main())
                .compose(RxProgress.applyProgressBar(this))
                .subscribe(new Consumer<HttpResult<PayResult>>() {
                    @Override
                    public void accept(HttpResult<PayResult> httpResult) throws Exception {
                        PayResult result = httpResult.data;
                        result.errorMessage = httpResult.msg;
                        result.setFlag(TopUpActivity.this,HomeCenter.SCHEME_TOP_UP);
                        if (httpResult.code == 0) {
                            PayOkActivity.start(TopUpActivity.this, result);
                        } else {
                            PayFailActivity.start(TopUpActivity.this, result);
                        }
                    }
                }, new RxException<>(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        PayResult result = new PayResult(TopUpActivity.this,HomeCenter.SCHEME_TOP_UP);
                        result.errorMessage = throwable.getMessage();
                    }
                }));
    }

    /**
     * 充值成功
     */
    @Override
    public void topUpOk() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddBankActivity.MANGER_CARD_CODE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Fragment fragment = getSupportFragmentManager().findFragmentByTag("into");
                if (fragment != null)
                    fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    @Override
    public KeyboardUtil getKeyboard() {
        if (keyboardUtil == null) {
            keyboardUtil = new KeyboardUtil(this, false);
        }
        return keyboardUtil;
    }

    @Override
    public Button getButton() {
        return confirm;
    }
}
